package com.xuebank.nfe.nfecar.utils.network

import com.readystatesoftware.chuck.ChuckInterceptor
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.MainActivity
import com.xuebank.nfe.nfecar.MyApplication
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.model.manager.UserInfoManager
import com.xuebank.nfe.nfecar.utils.network.converter.GsonConverterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by WindFantasy on 2016/12/1.
 */

object ServiceGenerator {
    /**
     * https://awakenuat-app.jujinpan.cn/  uat测试环境
     */
    val ROOT_URL_VERSION = "test.nfechefan.cn/nfeboot/"
    val ROOT_URL_VERSION_PRE = "test.nfechefan.cn/nfeboot/"
    val ROOT_URL_VERSION_UAT = "test.nfechefan.cn/nfeboot/"
    val ROOT_URL_VERSION_SIT = "test.nfechefan.cn/nfeboot/"
    private val httpClient by lazy {
        val client = OkHttpClient.Builder().addInterceptor(mInterceptor)
        client.readTimeout(60, TimeUnit.SECONDS)

            client.addNetworkInterceptor(ChuckInterceptor(MyApplication.myApplicationContext))
                    .addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        return@lazy client
    }

    private val builder = Retrofit.Builder()
            .baseUrl("http://"+ rootUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())

    val mInterceptor: InterceptorIMPL by lazy {
        InterceptorIMPL()
    }

    fun instance(): ServiceGenerator {
        return ServiceGenerator
    }

    fun <S> createService(serviceClass: Class<S>): S {
        val retrofit = builder.client(httpClient.build()).build()
        com.wzn.libaray.utils.Logger.d("进app的环境是","进app的环境是${rootUrl}")
        com.wzn.libaray.utils.Logger.d("进builder的环境是","进builder环境是${builder.client(httpClient.build()).build()}")
        return retrofit.create(serviceClass)
    }

    val rootUrl: String
        get() {
            val curServiceModel=Constants.getServiceModel() //todo
            return when (curServiceModel) {
                Constants.ServiceHostConfig.SERVICE_ONLINE -> ROOT_URL_VERSION
                Constants.ServiceHostConfig.SERVICE_PRE -> ROOT_URL_VERSION_PRE
                Constants.ServiceHostConfig.SERVICE_UAT -> ROOT_URL_VERSION_UAT
                Constants.ServiceHostConfig.SERVICE_SIT -> ROOT_URL_VERSION_SIT
                else -> ROOT_URL_VERSION

            }
        }


    class InterceptorIMPL : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val original = chain.request()
            val authorizedUrlBuilder = original.url()
                    .newBuilder()
                    .scheme(original.url().scheme())
                    .host(original.url().host())


            val requestBuilder = original.newBuilder()
                    .header("Cookie", SharedPreferencesUtil.getInstance(MyApplication.myApplicationContext).getString(MainActivity.COOKIE))
                    .header("Content-Type", "multipart/form-data")
                    .header("Accept", "application/json;charset=UTF-8")
                    .method(original.method(), original.body())
                    .url(authorizedUrlBuilder.build())
            Logger.d("cookie","cookie是什么  ${SharedPreferencesUtil.getInstance(MyApplication.myApplicationContext).getString(MainActivity.COOKIE)} ")

            val request = requestBuilder.build()
            return chain.proceed(request)
        }
    }
}
